<?php

namespace App\Providers;

use App\Models\Admin;
use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Boot the authentication services for the application.
     *
     * @return void
     */
    public function boot()
    {
        // Here you may define how you wish users to be authenticated for your Lumen
        // application. The callback which receives the incoming request instance
        // should return either a User instance or null. You're free to obtain
        // the User instance via an API token or any other method necessary.

        $this->app['auth']->viaRequest('api', function ($request) {
            $api_token = $request->input('api_token');
            if(empty($api_token) && isset($_COOKIE['api_token'])) {
                $api_token = $_COOKIE['api_token'];
            }
            if ($api_token) {
                return User::where('api_token', $api_token)
                    ->where('api_token_expire_at','>', date('Y-m-d H:i:s'))
//                    ->where('status', User::STATUS_ENABLED)
//                    ->where('synced_with_qyh', User::SYNCED)
                    ->first();
            }
        });

        $this->app['auth']->viaRequest('admin', function ($request) {
            $api_token = $request->input('api_token');
            if(empty($api_token) && isset($_COOKIE['api_token'])) {
                $api_token = $_COOKIE['api_token'];
            }
            if ($api_token) {
                return Admin::where('api_token', $api_token)
                    ->where('api_token_expire_time', '>', date('Y-m-d H:i:s', time()))
                    ->first();
            }
        });
    }
}
